package com.elvish.oda.busin.service;

import java.util.ArrayList;
import java.util.List;

import org.nutz.lang.Lang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.elvish.oda.busin.dao.AreaDao;
import com.elvish.oda.busin.pojo.Area;

@Component
public class AreaService {

	@Autowired
	private AreaDao areaDao;

	public List<Area> findAll() {
		return areaDao.findAll();
	}

	public Area findById(Integer id) {
		return areaDao.findById(id);
	}

	public int save(Area area) {
		return areaDao.save(area);
	}

	@Transactional
	public int deleteById(Integer id) {
		List<String> ids = new ArrayList<String>();
		List<Area> childrenList = areaDao.findByPid(id);
		// 根据id查询其下级所有数据id
		findById(childrenList, ids);
		// 自身
		ids.add(id.toString());
		// 删除所有数据
		areaDao.deleteByIds(ids.toArray(new String[ids.size()]));
		return 1;
	}

	public void findById(List<Area> childrenList, List<String> ids) {
		if (!Lang.isEmpty(childrenList)) {
			for (Area area : childrenList) {
				// 根据id查询pid为id的下级
				List<Area> childList = areaDao.findByPid(area.getId());
				ids.add(area.getId().toString());
				findById(childList, ids);
			}
		}
	}

	public int update(Area area) {
		return areaDao.update(area);
	}

}
